<template>
  <div class="formula-preview">
    <el-card class="preview-card">
      <template #header>
        <div class="card-header">
          <span>公式预览</span>
          <el-button
              type="primary"
              size="small"
              @click="copyLatex"
              :disabled="!latexContent"
          >
            复制 LaTeX
          </el-button>
        </div>
      </template>

      <div class="preview-content">
        <div
            v-if="latexContent"
            class="katex-render"
            v-html="renderedFormula"
        ></div>
        <div v-else class="empty-preview">
          <el-empty description="请输入公式内容" :image-size="80" />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import katex from 'katex';
import { ElMessage } from 'element-plus';

interface Props {
  latexContent: string;
}

const props = defineProps<Props>();

const renderedFormula = computed(() => {
  if (!props.latexContent) return '';

  try {
    return katex.renderToString(props.latexContent, {
      throwOnError: false,
      displayMode: true,
      output: 'html'
    });
  } catch (error) {
    return `<div class="error-message">公式渲染错误: ${error}</div>`;
  }
});

const copyLatex = async () => {
  try {
    await navigator.clipboard.writeText(props.latexContent);
    ElMessage.success('LaTeX 代码已复制到剪贴板');
  } catch (err) {
    ElMessage.error('复制失败');
  }
};
</script>

<style scoped>
.preview-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.preview-content {
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.katex-render {
  font-size: 1.2em;
  text-align: center;
}

.empty-preview {
  width: 100%;
}

.error-message {
  color: #f56c6c;
  font-size: 14px;
}
</style>
